package cn.chenddcoder.handler;

import cn.chenddcoder.operator.JoinOperator;
import cn.chenddcoder.operator.MessageOperator;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.socket.CloseStatus;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.handler.TextWebSocketHandler;

import java.nio.charset.StandardCharsets;
import java.util.*;
@Slf4j
public class ChatWebSocketHandler extends TextWebSocketHandler {
    @Autowired
    private JoinOperator joinOperator;
    @Autowired
    private MessageOperator messageOperator;
    @Override
    protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception {
        // 处理文本消息
        String payload = message.getPayload();
        ChatObject chatObject=JSONUtil.toBean(payload,ChatObject.class);
        boolean result=false;
        if (chatObject.getType()==null){
            System.out.println("请求体错误");
            session.close();
            return;
        }
        if (chatObject.getType().equals(ChatTypeEnum.JOIN.getValue())){
            result = joinOperator.join(chatObject.getGroupId(), getUserId(session));

        }else if(chatObject.getType().equals(ChatTypeEnum.GROUP.getValue())){
            result = joinOperator.group(chatObject.getGroupId(), message.getPayload());
        }
        if (result){
            session.sendMessage(new TextMessage(ChatReply.ok()));
        }else{
            session.sendMessage(new TextMessage(ChatReply.error()));
        }
    }

    @Override
    public void afterConnectionEstablished(WebSocketSession session) throws Exception {
        // 连接建立后的操作
        System.out.println("New connection: " + session.getId());
        String userId = getUserId(session);
        if (ObjectUtil.isEmpty(userId)){
            System.out.println("请求参数错误，断开连接");
            session.close();
        }else{
            messageOperator.add(userId,session);
        }
    }
    private String getUserId(WebSocketSession session){
        String userId=null;
        if (session.getUri()!=null){
            Map<String, String> params = HttpUtil.decodeParamMap(session.getUri().getQuery(), StandardCharsets.UTF_8);
            //token就是userId
            userId=params.get("token");
        }
        return userId;
    }
    @Override
    public void afterConnectionClosed(WebSocketSession session, CloseStatus status) throws Exception {
        String userId=getUserId(session);
        messageOperator.remove(userId);
        joinOperator.leave(userId);
        System.out.println("Connection closed: " + session.getId());

    }
}

